package com.newtouch.cq.base.starter.lang.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.newtouch.cq.base.starter.business.model.UserDetailsImpl;
import com.newtouch.cq.lang.em.BaseExceptionEnum;
import com.newtouch.cq.lang.exception.MccBizException;
import com.newtouch.cq.lang.util.LogUtil;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 当前用户工具
 *
 * @author alex
 * @Date: 2021/2/22
 */
public class CurrentUserUtil {

    private static Log log = LogFactory.get(CurrentUserUtil.class);

    /**
     * 获取当前用户，没有返回null
     * @return
     */
    public static UserDetailsImpl user() {
        UserDetailsImpl user = null;
        try {
            user = (UserDetailsImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (Exception e) {
            log.info("用户未登录");
        }
        return user;
    }

    /**
     * 获取当前用户，未登录抛出异常
     * @return
     */
    public static UserDetailsImpl userOrThrow() {
        UserDetailsImpl user = user();
        if(null == user) {
            LogUtil.error(log,BaseExceptionEnum.ACCREDIT_INVALID_OVERDUE);
            throw new MccBizException(BaseExceptionEnum.ACCREDIT_INVALID_OVERDUE);
        }
        return user;
    }

    /**
     * 获取当前用户id，未登录抛出异常
     * @return
     */
    public static long userIdOrThrow() {
        UserDetailsImpl user = userOrThrow();
        return user.getId();
    }

    /**
     * 获取当前用户id，未登录返回null
     * @return
     */
    public static Long userIdOrNull() {
        UserDetailsImpl user = user();
        return null == user ? null : user.getId();
    }

    /**
     * 查看是否拥有某个组织的权限
     * @param orgId
     * @return
     */
    public static boolean containsOrg(long orgId) {
        UserDetailsImpl user = userOrThrow();
        return user.getId() == 1 || CollUtil.contains(user.getOrgIdList(),orgId);
    }

    /**
     * 查看是否拥有某个组织的权限，没有抛出异常
     * @param orgId
     */
    public static void containsOrgOrThrow(long orgId) {
        if(!containsOrg(orgId)) {
            LogUtil.error(log,BaseExceptionEnum.FAIL,"权限不足！！！");
            throw new MccBizException(BaseExceptionEnum.FAIL).setMessage("权限不足");
        }
    }

}
